﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Mammoth.Entities;
using Mammoth.Navigations;
using Mammoth.Repositories;
using Mammoth.Services;
using Mammoth.Events;

namespace Mammoth.ViewModels
{
    public class AddValasViewModel : WPFViewModelBase
    {
        public string Name { get; set; }
        public decimal Sell { get; set; }
        public decimal Buy1 { get; set; }
        public decimal Buy2 { get; set; }
        public decimal Buy3 { get; set; }
        public decimal Type1 { get; set; }
        public decimal Type2 { get; set; }
        public decimal Type3 { get; set; }

        IRepositoryFactory repo;
        public AddValasViewModel(IInputElement dispatcher, IRepositoryFactory repo)
            : this(dispatcher, repo, null) { }
        AddValasArguments args;

        public AddValasViewModel(IInputElement dispatcher, IRepositoryFactory repo, object arguments)
            : base(dispatcher)
        {
            this.args = (AddValasArguments)arguments;
            this.repo = repo;
            if (arguments != null)
                ReloadForEditing(args.ValasId);
        }

        void ReloadForEditing(long id)
        {
            using (var rep = repo.GetRepository<ValasEntity>())
            {
                var entity = rep.Get(id);
                Name = entity.Name;
                Sell = entity.Sell;
                Buy1 = entity.Buy1;
                Buy2 = entity.Buy2;
                Buy3 = entity.Buy3;
                Type1 = entity.Type1;
                Type2 = entity.Type2;
                Type3 = entity.Type3;
            }
        }

        public void Save()
        {
            if (!Validate()) return;

            try
            {
                using (var r = repo.GetRepository<ValasEntity>())
                {
                    var entity = new ValasEntity()
                    {
                        Name = Name,
                        Sell = Sell,
                        Buy1 = Buy1,
                        Buy2 = Buy2,
                        Buy3 = Buy3,
                        Type1 = Type1,
                        Type2 = Type2,
                        Type3 = Type3
                    };

                    if (args != null)
                        entity.Id = args.ValasId;

                    r.Save(entity);
                }
                Dispatcher.RaiseNavigationEvent();
            }
            catch (Exception)
            {
                Dispatcher.RaiseErrorEvent("Gagal menyimpan ke database");
            }
        }
    }
}
